# -*- coding: utf-8 -*-
# @Time    : 2022/11/16 15:19
# @Author  : yangyuexiong
# @Email   : yang6333yyx@126.com
# @File    : main.py
# @Software: PyCharm


from openpyxl import Workbook

from commands.app_commands.Excel.excel_base.main import ExcelHandle, clear_range_tuple


class ExcelClearHandle(ExcelHandle):
    """清除"""

    def __init__(self, excel_path=None):
        super(ExcelClearHandle, self).__init__(excel_path=excel_path)

        self.clear_range_dict = {
            "cell": self.clear_cell,
            "a_line": self.clear_a_line,
            "one_column": self.clear_one_column,
            "all": self.clear_all,
            "custom_range": self.clear_custom_range
        }

    def clear_cell(self, sheet, row_num, column_num, **kwargs):
        """
        清除单元格数据
        :param sheet: sheet对象
        :param row_num: 行号
        :param column_num: 列号
        :param kwargs:
        :return:
        """

        print('=== clear_cell ===')
        cell = f"{column_num}{row_num}"
        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')

        try:
            # print(sheet[cell])
            # print(f"原数据:{sheet[cell].value}")
            sheet[cell].value = ''
        except BaseException as e:
            msg = f'清除:excel单元格: {cell} 失败'
            # print(msg)
            self.throw['status'] = False
            self.throw['message'] = msg
            return False

        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def clear_a_line(self, sheet, row_num, **kwargs):
        """
        清除一行数据
        :param sheet: sheet对象
        :param row_num: 行号
        :param kwargs:
        :return:
        """

        print('=== clear_a_line ===')
        sheet_rows = list(sheet.rows)
        max_row = sheet.max_row
        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')
        rn = int(row_num)
        # print(rn, max_row)

        if rn == 0 or rn - 1 > max_row:
            msg = f'清除失败：清除行号不能大于最大行数 {max_row} 或不能少于 0 '
            # print(msg)
            self.throw['status'] = False
            self.throw['message'] = msg
            return False

        for cell in sheet_rows[rn - 1]:
            self.set_cell_none(cell)

        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def clear_one_column(self, sheet, column_num, **kwargs):
        """
        清除一列数据
        :param sheet: sheet对象
        :param column_num: 列号
        :param kwargs:
        :return:
        """

        print('=== clear_one_column ===')
        sheet_columns = list(sheet.columns)
        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')
        col_index = None
        for index, i in enumerate(sheet_columns):
            if i[0].coordinate == f'{column_num}1':
                # print(i)
                col_index = index
                break

        if not col_index:
            msg = f'清除失败：清除列号：{column_num} 不存在或数据为空'
            # print(msg)
            self.throw['status'] = False
            self.throw['message'] = msg
            return False

        for cell in sheet_columns[col_index]:
            self.set_cell_none(cell)

        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def clear_all(self, sheet, **kwargs):
        """
        清除全表
        :param sheet: sheet对象
        :param kwargs:
        :return:
        """

        print('=== clear_all ===')

        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')

        for row in sheet.iter_rows():
            for cell in row:
                self.set_cell_none(cell)

        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def clear_custom_range(self, sheet, **kwargs):
        """
        清除自定义区间
        :param sheet: sheet对象
        :param kwargs: 起始行列，末尾行列
            {
                "start_row_num":"1",
                "start_column_num":"A",
                "end_row_num":"3",
                "end_column_num":"C",
            }
        """

        print('=== clear_custom_range ===')
        start_row_num = int(kwargs.get('start_row_num'))
        start_column_num = kwargs.get('start_column_num')
        end_row_num = int(kwargs.get('end_row_num'))
        end_column_num = kwargs.get('end_column_num')
        is_save_as = kwargs.get('is_save_as', False)
        new_path = kwargs.get('new_path')

        try:
            obj_list = sheet[f'{start_column_num}{start_row_num}':f'{end_column_num}{end_row_num}']
            if self.debug:
                print(obj_list)
        except BaseException as e:
            msg = f'清除失败：自定义区间错误，请检查'
            # print(msg)
            self.throw['status'] = False
            self.throw['message'] = msg
            return False

        for tup in obj_list:
            for cell in tup:
                self.set_cell_none(cell)

        self.excel_save_as(is_save_as=is_save_as, new_path=new_path)

    def excel_clear(self, sheet_name=None, clear_range=None, **kwargs):
        """
        清除
        :param sheet_name: sheet名称
        :param clear_range: 范围类型
        :param kwargs: 对应范围类型的扩展参数
        cell:
            行号，列号
            {
                "row_num":"1",
                "column_num":"A",
            }
        a_line:
            行号
            {
                "row_num":"1"
            }
        one_column:
            列号
            {
                "column_num":"A",
            }
        custom_range:
            起始行列，末尾行列
            {
                "start_row_num":"1",
                "start_column_num":"A",
                "end_row_num":"3",
                "end_column_num":"C",
            }
        all:
            全表
            {}
        :return:
        """

        try:
            if isinstance(self.wb, Workbook):
                self.wb.save(self.excel_path)
                # print(f"读取:{self.excel_path.split('/')[-1]}")

                if clear_range not in clear_range_tuple:
                    msg = f'读取范围错误:{clear_range}'
                    # print(msg)
                    self.throw['status'] = False
                    self.throw['message'] = msg
                    return self.throw

                if not self.check_sheet_name(sheet_name):
                    return self.throw

                sheet = self.get_sheet(sheet_name)
                kwargs['sheet'] = sheet
                clear_func = self.clear_range_dict.get(clear_range)
                clear_func(**kwargs)
                return self.throw

        except BaseException as e:
            print(e)
            self.return_error_file()
            return self.throw
